import router from '@/router/index';
import store from '@/store';

/**
 * bug复现 : 进入动态路由后刷新页面
 * 报错是发生在进入路由守卫之前的,路由匹配不到，所以出错
 * 执行流程 : 首先匹配指定的路由,匹配不到 -> 报错，页面大白
 *                             匹配到了 -> 进入路由守卫，开始执行
 * 解决思路 : 将动态路由放在路由守卫外面进行初始化，等待初始化完成后进行页面跳转
 */

router.beforeEach((to, from, next) => {
    const whiteList = ['/login'] // 白名单
    let token = store.getters.GET_TOKEN;
    let hasRoutes = store.state.hasRoutes;
    let menuList = store.getters.GET_MENULIST;
    
    if (token) {
        
        if (!hasRoutes) {
            bindRoute(menuList);
            store.commit('SET_ROUTES_STATE', true)
        }
        next();
    } else {
        if (whiteList.includes(to.path)) {
            next();
        } else {
            next('/login');
        }
    }
});



const bindRoute = (menuList) => {
    let newRoutes = router.options.routes;
    menuList.forEach(menu => {
        if (menu.children) {
            menu.children.forEach(m => {
                let route = menuToRoute(m, menu.name);
                if (route) {
                    newRoutes[0].children.push(route);
                }
            });
        }
    })
    // 重新添加到路由
    newRoutes.forEach(route=>{
        router.addRoute(route);
    });
}

// 菜单对象转换路由对象
const menuToRoute = (menu, parentName) => {
    if (!menu.component) {
        return null;
    }else {
        let route = {
            name: menu.name,
            path: menu.path,
            meta: {
                parentName: parentName
            }
        };
        route.component = () => import('@/views/' + menu.component + '.vue')
        return route;
    }
}
